package com.leetcode.partition10;

import java.util.HashMap;
import java.util.Map;

/**
 * @author `RKC`
 * @date 2021/11/3 17:10
 */
public class LC930和相同的二元子数组 {

    public static int numSubarraysWithSum(int[] nums, int goal) {
        return prefixSum(nums, goal);
    }

    private static int prefixSum(int[] nums, int goal) {
        int answer = 0, sum = 0;
        Map<Integer, Integer> count = new HashMap<>();
        count.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (count.containsKey(sum - goal)) {
                answer += count.get(sum - goal);
            }
            count.put(sum, count.getOrDefault(sum, 0) + 1);
        }
        return answer;
    }
}
